<!--
 * @Description:
 * @version:
 * @Author: 尹鹏孝
 * @Date: 2023-03-10 15:56:09
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2023-03-10 16:14:13
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>观察者模式</title>
</head>
<body>
    <script>
        function Observer(id){
            this.id=id;
            this.update = (obs)=>{
                console.log('观察者：',this.id);
                console.log('观察者：', obs.id);
            }
        }

        function Observed(){
            this.observers=[];
            this.addObserver = (obs)=>{
                this.observers.push(obs);
            }
            this.removeObserver = (obj)=>{
                this.observers = this.observers.filter(item=>item.id!=obs.id);
            }
            this.notify=(obs)=>{
                this.observers.forEach(item=>item.update(obs));
            }
        }

        const observed  = new Observed();

        const observers1 = new Observer(1);
        const observers2 = new Observer(2);
        const observers3 = new Observer(3);

        observed.addObserver(observers1);
        observed.addObserver(observers2);
        observed.addObserver(observers3);

        observed.notify(observers1);
    </script>
</body>
</html>